<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/5/8
 * Time: 17:15
 */

namespace app\admin\controller;

use app\admin\validate\Admin as validateAdmin;
use think\Db;
use think\facade\Hook;
use Zhuzhichao\IpLocationZh\Ip;

class User extends Base {
    public function __construct(){
        parent::__construct();
    }
    protected $sinkMethods = ['index','login'];
    /**
     * @route('admin/user/login','any')
     * @return \think\Response
     * @throws \Firebase\Token\TokenException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(){
        $admin = new validateAdmin;
        $data = request()->param();
        unset($data['pass']);
        if(!$admin->scene('login')->check($data)){
             $this->__e('',[
                'status'=>0,
                'msg'=>$admin->getError()
            ]);
        }
        Db::startTrans();
        $admin = new \app\admin\model\Admin;
        $_admin = $admin::where('username','eq',$data['username'])->find();
        if(!$_admin){
             $this->__e('账号不存在');
        }
        if($this->_password($data['password'],$_admin['hash'],1)!=$_admin['password']){
            $this->__e('密码错误');
        }
        if($_admin['status']!=1){
            $this->__e('账号已被锁定');
        }
        $token = $this->_token($_admin['id']);
//        p($token);die;
        unset($_admin['password']);
        unset($_admin['hash']);
        unset($_admin['update_time']);
        $ip = request()->ip();
        $location = Ip::find($ip);
        $address = implode(' ',$location);
        $_admin->last_ip = $ip;
        $_admin->last_date = time();
        $_admin->last_address= $address;
        $result = $_admin->save();
        $sql = $_admin->getLastSql();
        $_admin['access_token'] = $token ? $token['access_token'] : '';
        $_admin['expires_in'] = $token ? $token['expires_in'] : '';
        $params = [
            'aid'=>$_admin['id'],
            'action'=>"管理员【{$_admin['username']}】登陆系统",
            'sql'=>$sql
        ];
        Hook::listen('admin_log',$params);
        unset($_admin['code']);
        if($result){
            Db::commit();
            return $this->__s('',$_admin);
        }else{
            Db::rollback();
            return $this->__e('登陆失败');
        }
    }

    /**
     * 获取信息
     *@route('admin/user/info','get')
     * @return \think\Response
     * @throws \think\exception\DbException
     */
    public function info(){
        $admin = self::$user;
        if($admin['gid']==-1){
            $admin['roles'] = ['admin'];
        }else{
            if($admin['roles_gid']==-1){
                $admin['roles'] = ['admin'];
            }else{
                $admin['roles'] = $admin['roles']?$admin['roles']:[];
            }
        }
        return $this->__s('',$admin);
    }

    /**
     * @route('admin/user/save','post')
     */
    public function save(){
        $admin = new validateAdmin;
        $data = request()->post();
        if(!$admin->scene('save')->check($data)){
            return [
                'status'=>0,
                'msg'=>$admin->getError()
            ];
        }
        $admin = db('admin')
            ->field('id')
            ->where('username','eq',$data['username'])
            ->find();
        if(!$admin){
            return [
                'status'=>0,
                'msg'=>'管理员不存在'
            ];
        }
        $pwd = $this->_password($data['password'],1);
        if(!db('admin')->update([
            'id'=>$admin['id'],
            'password'=>$pwd,
            'dates'=>time()
        ])){
            return [
                'status'=>0,
                'msg'=>'修改失败'
            ];
        }
        return [
            'status'=>1,
            'msg'=>'修改成功'
        ];
    }

    /**
     * 退出
     * @route('admin/user/logout','post')
     */
    public function logout(){
        $username = self::$user['username'];
        Hook::listen('admin_log',['aid'=>self::$uid,'action'=>"管理员【{$username}】登出系统"]);
        $this->_removeToken();
        $this->__s('退出成功');
    }

    /**
     * @param int $guide
     * @return \think\Response
     * @route('admin/user/guide','get')
     */
    public function guide($guide=0){
        $info = (new \app\admin\model\Admin())->find(self::$uid);
        if(!$info){
            return $this->__e('不存在');
        }
        $info->guide = $guide;
        if(!$info->save()){
            return $this->__e('操作失败');
        }
        return $this->__s('操作成功');
    }
}